﻿using UnityEngine;
using System.Collections;

namespace Toolkit
{
	public class MonoSingleton<T>:MonoBehaviour
		where T : MonoSingleton<T>, new()
	{
		/// <summary>
		/// 检测实例是否为null的标志
		/// 用于解决unity new Object() == null 为true的情况
		/// </summary>
		private static bool instanceIsNull = true;
		//private static string MONO_SINGLETON_NAME = "Main";
		protected static T s_Instance = null;
		//private static GameObject gobj = null;
		private static object s_lock_instance = new object();

		public static T instance
		{
			get
			{
				lock (s_lock_instance)
				{
					if(instanceIsNull)
					{
						var ins = FindObjectOfType<T>();
						if(ins == null)
						{
							var gobj = FindGameObjectOrCreate("Main");
							ins = gobj.AddComponent<T>();
							ins.Init();
						}
						ins.AppyInstance();
					}
				}
				return s_Instance;
			}
		}
		public static GameObject FindGameObjectOrCreate(string tname)
		{
			var gobj = GameObject.Find(tname);
			if(gobj == null)
			{
				gobj = new GameObject(tname);
				DontDestroyOnLoad(gobj);
			}
			return gobj;
		}
		protected virtual void Awake()
		{
			AppyInstance();
		}
		protected void AppyInstance()
		{
			if(instanceIsNull)
			{
				s_Instance = this as T;
				instanceIsNull = false;
			}
		}
		protected virtual void Init()
		{
		}

		protected virtual void OnRelease()
		{
			s_Instance = null;
			instanceIsNull = true;
		}

		void OnDestroy()
		{
			OnRelease();
		}
	}
}